﻿
namespace TestFsWeb

open System
open System.Web

module TestHttpUtility =

    let private test_url_encode_decode() =
        // !!! this method cannot be used to encode the entire URL
        // !!! it can only be used to encode the 'key' and 'value' 
        // !!! parts within the query string
        // !!! then we have to construct the whole URL by ourselves
        "http://somewhere.net?value=hello stasi from wsu"
        |> HttpUtility.UrlEncode
        |> printfn "%s"

        let encoded =
            "hello F# from web"
            |> HttpUtility.UrlEncode
        printfn "encoded='%s'" encoded

        let decoded =
            encoded
            |> HttpUtility.UrlDecode
        printfn "decoded='%s'" decoded

    let private test_compose_querystring() =
        let namevalues = HttpUtility.ParseQueryString("")
        namevalues.Add("name","STASI CHEKA")
        namevalues.Add("value","KGB GRU")
        printfn "%O" namevalues

    // this test demonstrate that 'HttpUtility.ParseQueryString'
    // can be used to parse the encoded string returned by "JQuery.param"
    let private test_parse_querystring() =
        let namevalues = HttpUtility.ParseQueryString("a+thing=it%26s%3Dvalue&another+thing=another+value&weird+characters=!%40%23%24%25%5E%26*()_%2B%3D")
        for index = 0 to namevalues.Count-1 do
            printfn "[%d] Key=%s,Value=%s" (index+1) (namevalues.GetKey(index)) (namevalues.Get(index))

    let private test_uri() =
        let uri = new Uri("http://somewhere.net/hello?name=stasi rocks&name=cheka&rate=1")
        printfn "Host: %s" uri.Host
        printfn "OriginalString: %s" uri.OriginalString
        printfn "AbsolutePath: %s" uri.AbsolutePath
        printfn "Query: %s" uri.Query
        printfn "LocalPath: %s" uri.LocalPath

        let parameters = HttpUtility.ParseQueryString uri.Query
        for index = 0 to parameters.Count-1 do
            printfn "[%d] key='%s' value='%s'" index (parameters.GetKey(index)) (parameters.Get(index))


    let main() =
        // test_url_encode_decode()
        // test_compose_querystring()
        test_parse_querystring()
        // test_uri()



